﻿using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WinFormsAppSignalRClient
{
    internal class ClockHubClient : IHostedService
    {
        private readonly ILogger<ClockHubClient> _logger;
        private HubConnection _connection;

        public ClockHubClient(ILogger<ClockHubClient> logger)
        {
            _logger = logger;

            _connection = new HubConnectionBuilder()
                .WithUrl("https://localhost:51541/hubs/clock")
                .WithAutomaticReconnect()  // 会自动重新连接 默认是连接失败后等待 0 2 10 30 秒后重连
                                           //.WithAutomaticReconnect(new[] {100,2000,} )
                .Build();

            _connection.On<DateTime>("ShowTime", (time) =>
            {
                _logger.LogInformation($"Received time: {time}");
                // 这里可以更新UI或执行其他操作
            });
        }
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                _logger.LogInformation("Connecting to ClockHub...");
                await _connection.StartAsync(cancellationToken);
                _logger.LogInformation("Connected to ClockHub.");
            }
        }

        public async Task StopAsync(CancellationToken cancellationToken)
        {
            await _connection.StopAsync(cancellationToken);
        }
    }
}
